﻿using System;
using System.Collections.Generic;
using ArchPostprocessing.CompoundStructureManage.DataDefinition;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Architecture;
using YArchitech.Revit;
using TopologySearch;

namespace ArchPostprocessing.CompoundStructureManage.Managers
{
	public class RoomEdgeInfoManager
	{
		public RoomEdgeInfoManager(Autodesk.Revit.DB.Document doc)
		{
			this.m_Doc = doc;
			this.m_AllRoomEdgeInfo = this.GetRoomInfos();
		}

		private List<RoomEdgeLoopInfo> GetRoomInfos()
		{
			Transaction transaction = new Transaction(this.m_Doc, "Get room infos");
			transaction.Start();
			Level genLevel = this.m_Doc.ActiveView.GenLevel;
			this.RemoveRooms(genLevel);
			List<RoomEdgeLoopInfo> result = this.Create2ndGetRoomDataInfos(genLevel);
			transaction.RollBack();
			return result;
		}

		private List<RoomEdgeLoopInfo> Create2ndGetRoomDataInfos(Level level)
		{
			List<RoomEdgeLoopInfo> list = new List<RoomEdgeLoopInfo>();
			List<RoomEdgeLoopInfo> result;
			try
			{
				SpatialElementBoundaryOptions spatialElementBoundaryOptions = new SpatialElementBoundaryOptions();
				foreach (object obj in this.m_Doc.get_PlanTopology(level).Circuits)
				{
					PlanCircuit planCircuit = (PlanCircuit)obj;
					if (!planCircuit.IsRoomLocated)
					{
						try
						{
							SpatialElement spatialElement = this.m_Doc.Create.NewRoom(null, planCircuit);
							List<RoomBoundingSegment> list2 = new List<RoomBoundingSegment>();
							foreach (IList<BoundarySegment> list3 in spatialElement.GetBoundarySegments(spatialElementBoundaryOptions))
							{
								foreach (BoundarySegment segment in list3)
								{
									Element element = segment.GetElement(this.m_Doc);
									if (element != null && !(element.GetType() != typeof(FamilyInstance)))
									{
										Curve curve = segment.GetCurve();
										try
										{
											RoomBoundingSegment item = new RoomBoundingSegment(Pole2D.TransformWallToStructure2DPole(curve, ElementId.InvalidElementId, 0.0, 0.0), segment.GetElement(this.m_Doc).Id);
											list2.Add(item);
										}
										catch (Exception)
										{
										}
									}
								}
							}
							RoomEdgeLoopInfo item2 = new RoomEdgeLoopInfo(list2);
							list.Add(item2);
						}
						catch (Exception)
						{
						}
					}
				}
				result = list;
			}
			catch (Exception)
			{
				result = list;
			}
			return result;
		}

		private void RemoveRooms(Level level)
		{
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(this.m_Doc, this.m_Doc.ActiveView.Id).OfClass(typeof(SpatialElement));
			List<ElementId> list = new List<ElementId>();
			foreach (Element element in filteredElementCollector)
			{
				Room room = ((SpatialElement)element) as Room;
				if (room != null)
				{
					list.Add(room.Id);
				}
			}
			this.m_Doc.Delete(list);
		}

		private Document m_Doc;

		private List<RoomEdgeLoopInfo> m_AllRoomEdgeInfo = new List<RoomEdgeLoopInfo>();
	}
}
